package com.ly.heart.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ly.common.core.domain.AjaxResult;
import com.ly.common.exception.CustomException;
import com.ly.common.utils.DateUtils;
import com.ly.common.utils.SecurityUtils;
import com.ly.common.utils.erp.ConstUtil;
import com.ly.common.utils.erp.ReturnPage;
import com.ly.common.utils.erp.SnowflakeIdWorker;
import com.ly.heart.domain.*;
import com.ly.heart.domain.dto.StartProcessDto;
import com.ly.heart.domain.dto.SupplierQueryDto;
import com.ly.common.core.domain.ActCurrentTaskVo;
import com.ly.heart.domain.vo.SupplierQueryVo;
import com.ly.heart.mapper.AreaMapper;
import com.ly.heart.mapper.SupplierMapper;
import com.ly.heart.service.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

/**
 * 供应商Service业务层处理
 *
 * @author cxl
 * @date 2024-06-16
 */
@Service
public class SupplierServiceImpl extends ServiceImpl<SupplierMapper, SupplierEntity> implements ISupplierService {

    @Resource
    private SupplierMapper supplierMapper;
    @Resource
    private IBankInfoService bankInfoService;
    @Resource
    private ISupplierContactsService supplierContactsService;
    @Resource
    private ISupplierOrganizationService supplierOrganizationService;
    @Resource
    private IKingBaseContactsService kingBaseContactsService;
    @Resource
    private IActModelService iActModelService;
    @Resource
    private IActTaskCommentService actTaskCommentService;
    @Resource
    private AreaMapper areaMapper;

    /**
     * 新增供应商
     *
     * @param supplierEntity 供应商
     * @return 结果
     */
    @Override
    @Transactional ( rollbackFor = Exception.class, propagation = Propagation.REQUIRED )
    public AjaxResult draft ( SupplierEntity supplierEntity ) {
        String supplierId = SnowflakeIdWorker.getInstance ().nextStringId ();
        Date nowDate = DateUtils.getNowDate ();
        String userId = SecurityUtils.getLoginUser ().getUser ().getUserId ();
        supplierEntity.setId ( supplierId );
        supplierEntity.setCreateTime ( nowDate );
        supplierEntity.setUserId ( userId );
        String supplierCodePrefix = "VER";
        int count = this.count ();
        String supplierCodePrefixCountStr = String.format ( "%06d", count );
        supplierEntity.setSupplierCode ( supplierCodePrefix.concat ( supplierCodePrefixCountStr ) );
        if ( ! CollectionUtils.isEmpty ( supplierEntity.getContracts () ) ) {
            saveSupplierContracts(supplierEntity);
        }
        if ( ! CollectionUtils.isEmpty ( supplierEntity.getBanks () ) ) {
            saveSupplierBanks(supplierEntity);
        }
        if ( ! CollectionUtils.isEmpty ( supplierEntity.getOrganizations () ) ) {
            saveSupplierOrganizations(supplierEntity);
        }
        supplierEntity.setState ( ConstUtil.STATE_IN_DRAFT );
        supplierMapper.insertSupplierEntity ( supplierEntity );
        return AjaxResult.success ( "暂存供应商成功", supplierEntity.getId () );
    }

    @Override
    public AjaxResult submit ( SupplierEntity supplierEntity ) {
        if ( Objects.isNull ( supplierEntity.getId () ) ) {
            return AjaxResult.error ( "请先暂存该单据！" );
        }
        StartProcessDto startDto = new StartProcessDto ().setBusinessId ( supplierEntity.getId () ).setBusinessType ( supplierEntity.getBusinessType () ).setModelId ( supplierEntity.getModelId () ).setBusinessName ( "供应商_".concat ( supplierEntity.getId () ) );
        String instanceId = iActModelService.startProcess ( startDto );
        boolean update = this.update ( new LambdaUpdateWrapper<SupplierEntity> ().
                set ( SupplierEntity :: getState, ConstUtil.STATE_IN_PROCESS ).
                set ( SupplierEntity :: getInstanceId, instanceId ).
                eq ( SupplierEntity :: getId, supplierEntity.getId () ) );
        if ( ! update ) {
            throw new CustomException ( "提交供应商失败！" );
        }
        return AjaxResult.success ( "提交供应商成功" );
    }

    /**
     * 新增供应商联系人
     * @param supplier
     * @param contracts
     */
    private void saveSupplierContracts(SupplierEntity supplier){
        supplier.getContracts().forEach ( contract -> {
            contract.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
            contract.setSupplierId ( supplier.getId() );
            contract.setUserId ( supplier.getUserId() );
            contract.setCreateTime ( supplier.getCreateTime() );
            String prefix = "CXR";
            int contractsCount = supplierContactsService.count ();
            String countStr = String.format ( "%06d", contractsCount );
            contract.setContactsCode ( prefix.concat ( countStr ) );
        } );
        boolean saveBatch = supplierContactsService.saveBatch ( supplier.getContracts() );
        if ( ! saveBatch ) {
            throw new RuntimeException ( "新增供应商联系人失败！" );
        }
    }

    /**
     * 新增供应商银行账号信息
     * @param supplier
     * @param banks
     */
    private void saveSupplierBanks(SupplierEntity supplier){
        supplier.getBanks().forEach ( bank -> {
            bank.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
            bank.setRelationId ( supplier.getId() );
            bank.setType ( ConstUtil.SUPPLIER_TYPE_CUSTOMER );
        } );
        boolean saveBatch = bankInfoService.saveBatch ( supplier.getBanks() );
        if ( ! saveBatch ) {
            throw new RuntimeException ( "新增供应商务信息失败！" );
        }
    }

    /**
     * 新增供应商组织信息
     * @param supplier
     */
    private void saveSupplierOrganizations(SupplierEntity supplier){
        supplier.getOrganizations ().forEach ( organizationEntity -> {
            organizationEntity.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
            organizationEntity.setSupplierId ( supplier.getId() );
            organizationEntity.setCreateTime ( supplier.getCreateTime() );
            organizationEntity.setUserId ( supplier.getUserId() );
        } );
        boolean saveBatch = supplierOrganizationService.saveBatch ( supplier.getOrganizations () );
        if ( ! saveBatch ) {
            throw new RuntimeException ( "新增供应商组织信息失败！" );
        }
    }



    /**
     * 查询供应商详情
     * @param id 供应商ID
     * @return 供应商
     */
    @Override
    public SupplierEntity selectSupplierEntityById ( String id ) {
        SupplierEntity supplierEntity = supplierMapper.selectSupplierEntityById ( id );
        List<BankEntity> bankList = bankInfoService.list ( new QueryWrapper<BankEntity> ().eq ( "relation_id", id ).eq ( "type", ConstUtil.SUPPLIER_TYPE_CUSTOMER ) );
        if ( ! CollectionUtils.isEmpty ( bankList ) ) {
            supplierEntity.setBanks ( bankList );
        }
        List<SupplierContactsEntity> supplierContacts = supplierContactsService.list ( new QueryWrapper<SupplierContactsEntity> ().eq ( "supplier_id", id ) );
        if ( ! CollectionUtils.isEmpty ( supplierContacts ) ) {
            supplierContacts.forEach ( supplierContact -> {
                KingBaseContactsEntity kingBaseContactsEntity = kingBaseContactsService.getById ( supplierContact.getContactsId () );
                Optional.ofNullable ( kingBaseContactsEntity ).ifPresent ( kingBaseContact -> {
                    supplierContact.setKingBaseContacts ( kingBaseContact );
                } );
            } );
            supplierEntity.setContracts ( supplierContacts );
        }
        List<SupplierOrganizationEntity> organizationList = supplierOrganizationService.list ( new QueryWrapper<SupplierOrganizationEntity> ().eq ( "supplier_id", id ) );
        if ( ! CollectionUtils.isEmpty ( organizationList ) ) {
            supplierEntity.setOrganizations ( organizationList );
        }
        supplierEntity.setStateName ( supplierEntity.getState () );
        if(Objects.nonNull(supplierEntity.getNationId())){
            AreaEntity areaNation = areaMapper.getAreaById(supplierEntity.getNationId());
            if(Objects.nonNull(areaNation)){
                supplierEntity.setNationName(areaNation.getAreaName());
            }
        }
        if(Objects.nonNull(supplierEntity.getProvincesId())){
            AreaEntity provincesNation = areaMapper.getAreaById(supplierEntity.getProvincesId());
            if(Objects.nonNull(provincesNation)){
                supplierEntity.setProvincesName(provincesNation.getAreaName());
            }
        }
        if(Objects.nonNull(supplierEntity.getCityId())){
            AreaEntity cityNation = areaMapper.getAreaById(supplierEntity.getCityId());
           if(Objects.nonNull(cityNation)){
               supplierEntity.setCityName(cityNation.getAreaName());
           }
        }
        return supplierEntity;
    }

    /**
     * 查询供应商列表
     * @param supplierEntity 供应商
     * @return 供应商
     */
    @Override
    public List<SupplierEntity> selectSupplierEntityList ( SupplierEntity supplierEntity ) {
        supplierEntity.setPage ( ( supplierEntity.getPage () - 1 ) * supplierEntity.getLimit () );
        List<SupplierEntity> supplierList = supplierMapper.selectSupplierEntityList ( supplierEntity );
        if ( ! CollectionUtils.isEmpty ( supplierList ) ) {
            supplierList.stream ().forEach ( supplier -> {
                List<BankEntity> bankList = bankInfoService.list ( new QueryWrapper<BankEntity> ().eq ( "relation_id", supplier.getId () ).eq ( "type", ConstUtil.SUPPLIER_TYPE_CUSTOMER ) );
                if ( ! CollectionUtils.isEmpty ( bankList ) ) {
                    supplier.setBanks ( bankList );
                }
                List<SupplierContactsEntity> supplierContacts = supplierContactsService.list ( new QueryWrapper<SupplierContactsEntity> ().eq ( "supplier_id", supplier.getId () ) );
                if ( ! CollectionUtils.isEmpty ( supplierContacts ) ) {
                    supplierContacts.forEach ( supplierContact -> {
                        KingBaseContactsEntity kingBaseContactsEntity = kingBaseContactsService.getById ( supplierContact.getContactsId () );
                        Optional.ofNullable ( kingBaseContactsEntity ).ifPresent ( kingBaseContact -> {
                            supplierContact.setKingBaseContacts ( kingBaseContact );
                        } );
                    } );
                    supplier.setContracts ( supplierContacts );
                }
                List<SupplierOrganizationEntity> organizationList = supplierOrganizationService.list ( new QueryWrapper<SupplierOrganizationEntity> ().eq ( "supplier_id", supplier.getId () ) );
                if ( ! CollectionUtils.isEmpty ( organizationList ) ) {
                    supplier.setOrganizations ( organizationList );
                }
                //流程状态名称
                supplier.setStateName ( supplier.getState () );
                //审批人信息
                ActTaskCommentEntity actTaskComment = actTaskCommentService.queryLastComment(supplier.getInstanceId());
                Optional.ofNullable(actTaskComment).ifPresent(taskComment -> {
                    supplier.setApprovedUser(taskComment.getApprovedUser());
                    supplier.setRemark(taskComment.getRemark());
                });
                //任务信息
                ActCurrentTaskVo currentTaskVo = iActModelService.getCurrentTaskByInstanceId(supplier.getInstanceId());
                Optional.ofNullable(currentTaskVo).ifPresent(currentTask -> {
                    supplier.setCurrentTask(currentTask);
                });
            } );
        }
        return supplierList;
    }

    @Override
    public Integer queryCount ( SupplierEntity supplierEntity ) {
        Integer integer = supplierMapper.queryCount ( supplierEntity );
        return integer;
    }

    /**
     * 修改供应商
     *
     * @param supplierEntity 供应商
     * @return 结果
     */
    @Override
    public int updateSupplierEntity ( SupplierEntity supplierEntity ) {
        //先删除
        removeSupplierOtherInfo(supplierEntity.getId());
        if ( ! CollectionUtils.isEmpty ( supplierEntity.getContracts () ) ) {
            saveSupplierContracts(supplierEntity);
        }
        if ( ! CollectionUtils.isEmpty ( supplierEntity.getBanks () ) ) {
            saveSupplierBanks(supplierEntity);
        }
        if ( ! CollectionUtils.isEmpty ( supplierEntity.getOrganizations () ) ) {
            saveSupplierOrganizations(supplierEntity);
        }
        supplierEntity.setChangeId ( SecurityUtils.getLoginUser ().getUser ().getUserId () );
        supplierEntity.setChangeTime ( DateUtils.getNowDate () );
        return supplierMapper.updateSupplierEntity ( supplierEntity );
    }

    @Override
    public AjaxResult disable ( String id ) {
        SupplierEntity supplierEntity = this.getById ( id );
        if ( supplierEntity == null ) {
            throw new CustomException ( "无此供应商！" );
        }
        boolean update = this.update ( new LambdaUpdateWrapper<SupplierEntity> ().
                set ( SupplierEntity :: getIsDisabled, supplierEntity.getIsDisabled () == 1 ? 2 : 1 ).
                set ( SupplierEntity :: getChangeTime, DateUtils.getNowDate () ).
                set ( SupplierEntity :: getChangeId, SecurityUtils.getLoginUser ().getUser ().getUserId () ).
                eq ( SupplierEntity :: getId, id ) );
        if ( ! update ) {
            throw new CustomException ( supplierEntity.getIsDisabled () == 1 ? "禁用供应商失败！" : "解禁供应商失败！" );
        }
        return AjaxResult.success ( supplierEntity.getIsDisabled () == 1 ? "禁用供应商成功！" : "解禁供应商成功！" );
    }

    private void removeSupplierOtherInfo(String supplierId){
        supplierContactsService.remove ( new LambdaQueryWrapper<SupplierContactsEntity>().eq ( SupplierContactsEntity::getSupplierId, supplierId ) );
        bankInfoService.remove ( new LambdaQueryWrapper<BankEntity> ().eq ( BankEntity::getRelationId, supplierId ).eq ( BankEntity::getType, ConstUtil.SUPPLIER_TYPE_CUSTOMER ) );
        supplierOrganizationService.remove ( new LambdaQueryWrapper<SupplierOrganizationEntity> ().eq ( SupplierOrganizationEntity::getSupplierId, supplierId ) );
    }

    /**
     * 批量删除供应商
     * @param ids 需要删除的供应商ID
     * @return 结果
     */
    @Override
    public int deleteSupplierEntityByIds ( String[] ids ) {
        for ( String id : ids ) {
            removeSupplierOtherInfo(id);
        }
        return supplierMapper.deleteSupplierEntityByIds ( ids );
    }

    /**
     * 删除供应商信息
     * @param id 供应商ID
     * @return 结果
     */
    @Override
    public int deleteSupplierEntityById ( String id ) {
        removeSupplierOtherInfo(id);
        return supplierMapper.deleteSupplierEntityById ( id );
    }

    @Override
    public AjaxResult getSupplier(SupplierQueryDto queryDto) {
        List<SupplierQueryVo> list = supplierMapper.getSupplier(queryDto);
        Page<SupplierQueryVo> page = new Page<>(queryDto.getPage(),queryDto.getLimit());
        return AjaxResult.success(ReturnPage.getReturnPage(page,list));
    }


}
